<template>
  <view class="app-pay-wrap">
    <view class="text">充值金额：{{ data.payValue }}元</view>
    <view class="text">充值状态：{{ data.resStatus }}</view>
    <button
      class="bnt-wrap"
      open-type="launchApp"
      app-parameter="wechat"
      @launchapp="launchAppSuccess"
      @error="launchAppError"
      @tap="backApp">
      返回APP
    </button>
  </view>
</template>

<script lang="ts" setup>
import { queryOpenId, unifiedAppOrder } from '@/service/apis/mine';
import { uniLogin } from '@/utils/api';
import { mathMultiplys } from '@/utils/maths';
// #ifdef MP-WEIXIN
import { useToast } from '@/components/wxToast';
import { setToastInstance } from '@/mixins/info';
setToastInstance(useToast());
// #endif

const $toast: any = inject('$Toast');

const data = reactive({
  resStatus: '充值中',
  openId: '',
  userId: '',
  payValue: 0,
  activityId: '',
});

const recharge = () => {
  const moneyVal = mathMultiplys(data.payValue, 100);
  console.log('222-----', data.userId);
  const obj: any = {
    userId: data.userId,
    source: 0,
    totalMoney: moneyVal,
    openId: data.openId,
  };
  if (data.activityId) {
    obj.activityId = data.activityId;
  }
  unifiedAppOrder(obj).then((res: any) => {
    uni.requestPayment({
      orderInfo: '',
      provider: 'wxpay',
      timeStamp: res.timeStamp,
      nonceStr: res.nonceStr,
      package: res.packageVal,
      signType: res.signType,
      paySign: res.paySign,
      success: (pay: any) => {
        console.log('success:' + JSON.stringify(pay));
        $toast('支付操作成功');
        data.resStatus = '支付成功';
        uni.navigateBack();
      },
      fail: (err: any) => {
        console.log('fail:' + JSON.stringify(err));
        $toast('支付操作失败');
        data.resStatus = '支付失败';
      },
    });
  });
};

const getOpenId = async () => {
  // 获取code
  const code = await uniLogin('weixin');
  if (!code) {
    data.resStatus = '获取code失败';
    return;
  }
  queryOpenId({ code: code }).then((res: any) => {
    if (res) {
      data.openId = res;
      recharge();
    } else {
      data.resStatus = '获取openId失败';
    }
  });
};

const backApp = () => {};

onLoad((options: any) => {
  console.log('options', options);
  if (options) {
    data.userId = options.userId;
    data.payValue = options.payValue;

    getOpenId();
  }
});

const launchAppSuccess = () => {
  // this.toast('返回成功');
};
const launchAppError = (e: any) => {
  $toast(e.detail.errMsg);
};
</script>

<style lang="scss" scoped>
.app-pay-wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  font-size: 14px;
  color: $uni-color-primary;

  .text {
    margin-bottom: 10px;
    line-height: 22px;
  }
}
</style>